package com.splant.android.smart.UILevel.Community;


import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.splant.android.R;
import com.splant.android.smart.CommunicationLevel.sPlantAsyncHttpClient;
import com.splant.android.smart.CommunicationLevel.sPlantJsonHttpResponseHandler;
import com.splant.android.smart.Global;
import com.splant.android.smart.ModelLevel.AreaListBean;
import com.splant.android.smart.ModelLevel.DetectorListBean;
import com.splant.android.smart.ModelLevel.event.AddPageEvent;
import com.splant.android.smart.SystemDefinedLevel.Utils.System_Dimen_Util;
import com.splant.android.smart.UILevel.Community.fragments.Garden_AreaList_Adapter;
import com.splant.android.smart.UILevel.Community.fragments.Garden_DetectorDatas_Fragment;
import com.splant.android.smart.UILevel.System_ViewPagerStateFragment_Adapter;
import org.apache.http.Header;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import de.greenrobot.event.EventBus;

public class Garden_DetectorList_Activity extends FragmentActivity implements View.OnClickListener {

    private TextView tv_areaName;
    private RecyclerView rlv_detectorList;

    private LinearLayout ll_soilTemperature;
    private LinearLayout ll_soilHumidity;
    private LinearLayout ll_soilNutrient;
    private DetectorListBean.Detector detector;
    private TextView tv_detectorName;
    private ImageView img_plant;
    private TextView tv_plantName;
    private ViewPager vp_detectorDatas;

    private TextView tv_tempture;
    private ImageView img_soilHumidity0;
    private ImageView img_soilHumidity1;
    private ImageView img_soilHumidity2;
    private ImageView img_soilHumidity3;
    private ImageView img_soilHumidity4;

    private ImageView img_soilNutrien0;
    private ImageView img_soilNutrien1;
    private ImageView img_soilNutrien2;
    private ImageView img_soilNutrien3;
    private ImageView img_soilNutrien4;

    private Garden_Detector_Adapter garden_detector_adapter;
    private List<DetectorListBean.Detector> detectorList = new ArrayList<>();

    private Button btn_goBack;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.garden_detectorlist_activity);

        tv_areaName = (TextView) findViewById(R.id.tv_areaName);
        btn_goBack = (Button) findViewById(R.id.btn_goBack);

        rlv_detectorList = (RecyclerView) findViewById(R.id.rlv_detectorList);
        tv_detectorName = (TextView) findViewById(R.id.tv_detectorName);
        img_plant = (ImageView) findViewById(R.id.img_plant);
        tv_plantName = (TextView) findViewById(R.id.tv_plantName);

        ll_soilTemperature = (LinearLayout) findViewById(R.id.ll_soilTemperature);
        ll_soilHumidity = (LinearLayout) findViewById(R.id.ll_soilHumidity);
        ll_soilNutrient = (LinearLayout) findViewById(R.id.ll_soilNutrient);
        vp_detectorDatas = (ViewPager) findViewById(R.id.vp_paraDatas);

        tv_tempture = (TextView) findViewById(R.id.tv_tempture);

        img_soilHumidity0 = (ImageView) findViewById(R.id.img_soilHumidity0);
        img_soilHumidity1 = (ImageView) findViewById(R.id.img_soilHumidity1);
        img_soilHumidity2 = (ImageView) findViewById(R.id.img_soilHumidity2);
        img_soilHumidity3 = (ImageView) findViewById(R.id.img_soilHumidity3);
        img_soilHumidity4 = (ImageView) findViewById(R.id.img_soilHumidity4);

        img_soilNutrien0 = (ImageView) findViewById(R.id.img_soilNutrien0);
        img_soilNutrien1 = (ImageView) findViewById(R.id.img_soilNutrien1);
        img_soilNutrien2 = (ImageView) findViewById(R.id.img_soilNutrien2);
        img_soilNutrien3 = (ImageView) findViewById(R.id.img_soilNutrien3);
        img_soilNutrien4 = (ImageView) findViewById(R.id.img_soilNutrien4);


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rlv_detectorList.setLayoutManager(linearLayoutManager);

        init();

        btn_goBack.setOnClickListener(this);
        tv_areaName.setOnClickListener(this);
        ll_soilTemperature.setOnClickListener(this);
        ll_soilHumidity.setOnClickListener(this);
        ll_soilNutrient.setOnClickListener(this);

        EventBus.getDefault().register(this);

    }

    private void init() {

        sPlantClient = sPlantAsyncHttpClient.getInstance();

        ll_soilTemperature.setBackgroundResource(R.color.garden_color1);

        FragmentManager mFragmentManager = getSupportFragmentManager();

        mViewPagerFragmentAdapter = new System_ViewPagerStateFragment_Adapter(mFragmentManager, mList);
        vp_detectorDatas.addOnPageChangeListener(new ViewPagetOnPagerChangedLisenter());
        vp_detectorDatas.setAdapter(mViewPagerFragmentAdapter);

        getDetectorList();
    }

    private void getDetectorList() {
        RequestParams params = new RequestParams();
        params.put("userId", Global.user.getUserId());
        params.put("pageNo", -1);
       // params.put("pageSize", 1000);
        params.put("isAutoTimer", 0);

        if (areaId.equals("") == false)
            params.put("areaId", areaId);

        sPlantClient.get(sPlantAsyncHttpClient.GETDETECTORDEVICES, params, new sPlantJsonHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    if (response.getInt("succeed") == 1) {

                        Gson gson = new Gson();
                        detectorList.clear();
                        DetectorListBean detectorListBean = gson.fromJson(response.toString(), DetectorListBean.class);

                        if (detectorListBean.getDetectorList() != null && detectorListBean.getDetectorList().size() > 0) {

                            detectorList.addAll(detectorListBean.getDetectorList());
                            detector = detectorList.get(0);
                            selectedTemptureParamter();
                        } else {
                            detector = null;
                            areaNoDetectors();
                        }
                        garden_detector_adapter = new Garden_Detector_Adapter(Garden_DetectorList_Activity.this, detectorList);
                        rlv_detectorList.setAdapter(garden_detector_adapter);

                        showDatas();

                        garden_detector_adapter.setOnItemClickListener(new Garden_Detector_Adapter.onItemClickListener() {
                            @Override
                            public void onItemChick(int pos) {

                                detector = detectorList.get(pos);
                                garden_detector_adapter.notifyDataSetChanged();
                                selectedTemptureParamter();
                                showDatas();

                            }
                        });

                        if (detectorList.size()==0)
                        {
                            Toast.makeText(Garden_DetectorList_Activity.this,"该区域没有检测器！",Toast.LENGTH_SHORT).show();
                        }

                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {

                Toast.makeText(Garden_DetectorList_Activity.this, getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void areaNoDetectors() {
        mList.clear();
        mViewPagerFragmentAdapter.notifyDataSetChanged();
        tv_tempture.setText("");
        img_soilHumidity0.setVisibility(View.GONE);
        img_soilHumidity1.setVisibility(View.GONE);
        img_soilHumidity2.setVisibility(View.GONE);
        img_soilHumidity3.setVisibility(View.GONE);
        img_soilHumidity4.setVisibility(View.GONE);

        img_soilNutrien0.setVisibility(View.GONE);
        img_soilNutrien1.setVisibility(View.GONE);
        img_soilNutrien2.setVisibility(View.GONE);
        img_soilNutrien3.setVisibility(View.GONE);
        img_soilNutrien4.setVisibility(View.GONE);

    }

    private void showDatas() {
        if (detector == null)
            return;
        tv_tempture.setText(detector.getTemperature() + "℃");

        if (detector.getHumidity().equals("1")) {
            img_soilHumidity0.setImageResource(R.mipmap.garden_ic_detector_soilhumidity_abnormal);
            img_soilHumidity1.setImageResource(R.mipmap.garden_ic_detector_soilhumidity_abnormal);
            img_soilHumidity0.setVisibility(View.VISIBLE);
            img_soilHumidity1.setVisibility(View.VISIBLE);
        } else if (detector.getHumidity().equals("2")) {
            img_soilHumidity0.setVisibility(View.VISIBLE);
            img_soilHumidity1.setVisibility(View.VISIBLE);
            img_soilHumidity2.setVisibility(View.VISIBLE);
        } else if (detector.getHumidity().equals("3")) {
            img_soilHumidity0.setVisibility(View.VISIBLE);
            img_soilHumidity1.setVisibility(View.VISIBLE);
            img_soilHumidity2.setVisibility(View.VISIBLE);
            img_soilHumidity3.setVisibility(View.VISIBLE);
            img_soilHumidity4.setVisibility(View.VISIBLE);
        }
        else
        {
            img_soilHumidity0.setVisibility(View.GONE);
            img_soilHumidity1.setVisibility(View.GONE);
            img_soilHumidity2.setVisibility(View.GONE);
            img_soilHumidity3.setVisibility(View.GONE);
            img_soilHumidity4.setVisibility(View.GONE);
        }

        if (detector.getSoilNutrient().equals("1")) {
            img_soilNutrien0.setImageResource(R.mipmap.garden_ic_detector_soilnutrient_abnormal);
            img_soilNutrien1.setImageResource(R.mipmap.garden_ic_detector_soilnutrient_abnormal);
            img_soilNutrien0.setVisibility(View.VISIBLE);
            img_soilNutrien1.setVisibility(View.VISIBLE);
        } else if (detector.getSoilNutrient().equals("2")) {
            img_soilNutrien0.setVisibility(View.VISIBLE);
            img_soilNutrien1.setVisibility(View.VISIBLE);
            img_soilNutrien2.setVisibility(View.VISIBLE);
        } else if (detector.getSoilNutrient().equals("3")) {
            img_soilNutrien0.setVisibility(View.VISIBLE);
            img_soilNutrien1.setVisibility(View.VISIBLE);
            img_soilNutrien2.setVisibility(View.VISIBLE);
            img_soilNutrien3.setVisibility(View.VISIBLE);
            img_soilNutrien4.setVisibility(View.VISIBLE);
        }
        else
        {
            img_soilNutrien0.setVisibility(View.GONE);
            img_soilNutrien1.setVisibility(View.GONE);
            img_soilNutrien2.setVisibility(View.GONE);
            img_soilNutrien3.setVisibility(View.GONE);
            img_soilNutrien4.setVisibility(View.GONE);
        }

        mList.clear();

        mList.add(new Garden_DetectorDatas_Fragment(detector, 0, 0));
        mViewPagerFragmentAdapter.notifyDataSetChanged();
    }

    private List<AreaListBean.Area> areaList = new ArrayList<>();
    private String areaId = "";
    private boolean isGetAreaId = false;

    private void showAreaList() {

        if (isGetAreaId)
            return;

        isGetAreaId = true;

        View popupView = getLayoutInflater().inflate(R.layout.garden_arealist_popupwindow, null);

        final ListView lv_areaList = (ListView) popupView.findViewById(R.id.lv_areaList);

        final PopupWindow window = new PopupWindow(popupView, System_Dimen_Util.dip2px(this, 200), System_Dimen_Util.dip2px(this, 400));

        window.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

        window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F8F8F8")));

        window.setFocusable(true);

        window.setOutsideTouchable(true);

        window.showAsDropDown(tv_areaName, 0, 0);

        RequestParams params = new RequestParams();
        params.put("userId", Global.user.getUserId());

        lv_areaList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                window.dismiss();

                areaId = areaList.get(position).getAreaId();
                tv_areaName.setText(areaList.get(position).getAreaName());
                detectorList.clear();

                getDetectorList();

            }
        });

        sPlantClient.get(sPlantAsyncHttpClient.GETAREALIST, params, new sPlantJsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        try {
                            isGetAreaId = false;
                            if (response.getInt("succeed") == 1) {

                                Gson gson = new Gson();
                                AreaListBean areaListBean = gson.fromJson(response.toString(), AreaListBean.class);


                                if (areaListBean.getAreaList() != null && areaListBean.getAreaList().size() > 0) {

                                    areaList.clear();

                                    AreaListBean.Area areaAll = new AreaListBean.Area();
                                    areaAll.setAreaId("");
                                    areaAll.setAreaName("全部区域");

                                    areaList.add(areaAll);
                                    areaList.addAll(areaListBean.getAreaList());

                                    Garden_AreaList_Adapter garden_areaList_adapter = new Garden_AreaList_Adapter(Garden_DetectorList_Activity.this, areaList);

                                    lv_areaList.setAdapter(garden_areaList_adapter);

                                }

                            }
                        } catch (Exception e) {


                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        isGetAreaId = false;
                        Toast.makeText(Garden_DetectorList_Activity.this, getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
                    }
                }
        );
    }

    private sPlantAsyncHttpClient sPlantClient;
    private System_ViewPagerStateFragment_Adapter mViewPagerFragmentAdapter;
    private List<Fragment> mList = new ArrayList<Fragment>();
    private int paraType;

    public void onEventMainThread(AddPageEvent addPageEvent) {
        //  Log.i("Detector","添加页面");

        mList.add(new Garden_DetectorDatas_Fragment(detector, paraType, mList.size()));

        mViewPagerFragmentAdapter.notifyDataSetChanged();

        vp_detectorDatas.setCurrentItem(mList.size() - 2);

    }

    private void selectedTemptureParamter()
    {
        ll_soilTemperature.setBackgroundResource(R.color.garden_color1);
        ll_soilHumidity.setBackgroundResource(R.color.garden_color0);
        ll_soilNutrient.setBackgroundResource(R.color.garden_color0);
    }
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_goBack:
                finish();
                break;
            case R.id.tv_areaName:
                showAreaList();
                break;
            case R.id.ll_soilTemperature:

                selectedTemptureParamter();
                paraType = 0;
                selectParamter();

                break;
            case R.id.ll_soilHumidity:

                ll_soilTemperature.setBackgroundResource(R.color.garden_color0);
                ll_soilHumidity.setBackgroundResource(R.color.garden_color1);
                ll_soilNutrient.setBackgroundResource(R.color.garden_color0);
                paraType = 1;
                selectParamter();
                break;
            case R.id.ll_soilNutrient:

                ll_soilTemperature.setBackgroundResource(R.color.garden_color0);
                ll_soilHumidity.setBackgroundResource(R.color.garden_color0);
                ll_soilNutrient.setBackgroundResource(R.color.garden_color1);

                paraType = 2;
                selectParamter();
                break;
        }
    }

    private void selectParamter() {
        for (Fragment fragment : mList) {
            ((Garden_DetectorDatas_Fragment) fragment).selectedPara(paraType);
        }
    }

    private final int MAX_DAY_COUNT = 10;
    private int curPageNo;

    private class ViewPagetOnPagerChangedLisenter implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

            if (position < MAX_DAY_COUNT) {
                if (position > curPageNo && position == mList.size() - 1) {
                    // Log.i("Detector","加载数据");
                    ((Garden_DetectorDatas_Fragment) mList.get(position)).getDatas();
                }
            }
            // Log.i("Detector","页面变更");
            if (position == 0 && position < curPageNo && mList.size() > 1) {
                Toast.makeText(Garden_DetectorList_Activity.this, "已经到达最前数据了", Toast.LENGTH_SHORT).show();
            }
            curPageNo = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
